package com.qidian.test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import com.qidian.common.Constants;

public class GetAnswerByUDP extends Thread{
	
	public static int getTimes = 1 ;
	public static int num_threads = 5 ;
	public static String destIP = "121.10.133.116" ;
	public static int destPort = Constants.portGetAnswer ;
	
	String msgId = "123456" ;
	
	public GetAnswerByUDP(String msgId)
	{
		this.msgId = msgId ;
	}
	
	public void run()
	{
        DatagramSocket client;
		try {
			client = new DatagramSocket();
			client.setSoTimeout(5000) ;
	        String sendStr = msgId;
	        byte[] sendBuf;
	        sendBuf = sendStr.getBytes();
	        InetAddress addr = InetAddress.getByName(destIP);
//	        int port = Constants.portGetAnswer;
	        DatagramPacket sendPacket 
	            = new DatagramPacket(sendBuf ,sendBuf.length , addr , destPort);
	        
	        for (int i = 0 ; i < getTimes ; i ++)
	        {
		        client.send(sendPacket);
		        byte[] recvBuf = new byte[100];
		        DatagramPacket recvPacket
		            = new DatagramPacket(recvBuf , recvBuf.length);
		        client.receive(recvPacket);
		        String recvStr = new String(recvPacket.getData() , 0 ,recvPacket.getLength());
		        System.out.println("收到:" + recvStr);
	        }
	        client.close();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
    public static void main(String[] args)throws IOException
    {
    	Thread[] threads = new GetAnswerByUDP[num_threads] ;
    	for(int i = 0 ; i < num_threads ; i ++)
    		threads[i] = new GetAnswerByUDP("123") ;
    	
    	for (int i = 0 ; i < num_threads ; i++)
    		threads[i].start() ;
    }

}
